/** Run this file to generate the types for the config */

/* eslint-disable @typescript-eslint/no-var-requires */

import fs from "fs";
import dtsGen from "dts-gen";
import path from "path";
import _ from "lodash";
import { parseIni, processRawConfig } from "./helpers.mjs";

function resolveRootPath() {
  const __dirname = path.resolve();
  const dirpath = path.resolve(__dirname);
  if (dirpath.includes("node_modules")) {
    return dirpath.split("node_modules")[0];
  }
  return dirpath;
}

export function generateConfigTypes() {
  const rootPath = resolveRootPath();

  const rawConfig = fs.readFileSync(
    path.join(rootPath, "default.config.ini"),
    "utf-8"
  );

  const config = parseIni(rawConfig);

  const processedConfig = processRawConfig(config);

  const result =
    "// THIS FILE IS AUTOGENERATED BY typesGenerator.js\n" +
    dtsGen
      .generateIdentifierDeclarationFile("IBksConfig", processedConfig)
      .replace("declare const IBksConfig:", "declare interface IBksConfig");

  fs.writeFileSync(
    path.join(rootPath, "src/typings/bksConfig.d.ts"),
    result
  );
}

if (process.env.CLI_MODE) {
  generateConfigTypes();
}
